const {request, showTip} = require("../common/request");
const {requestPromise} = require("./request");

// 假设从后端获取到了上传凭证 uptoken
let uptoken = '';
const qiniuDomain = 'suaq7cbei.hn-bkt.clouddn.com'; // 七牛云存储空间的域名

// 封装七牛云图片上传函数
function uploadImageToQiniu(successCallback, failCallback) {
    wx.chooseImage({
        count: 1,
        success: (res) => {
            const filePath = res.tempFilePaths[0];
            const fileName = new Date().getTime() + '.jpg';
            console.log("filePath:" + filePath);
            console.log("开始把微信小程序临时文件上传到七牛云");
            request({
                url: '/yoga_business/wechat/qiniu/getUploadToken',
                method: 'GET',
                data: {},
                success(res) {
                    if (res.success) {
                        console.log("uptoken:" + res.content);
                        const uptokenTemp = res.content;
                        wx.uploadFile({
                            url: 'https://up-z2.qiniup.com',
                            filePath,
                            name: 'file',
                            formData: {
                                key: fileName,
                                token: uptokenTemp
                            },
                            success: (uploadRes) => {
                                console.log(uploadRes);
                                if (uploadRes.statusCode === 200) {
                                    const result = JSON.parse(uploadRes.data);
                                    const fileKey = `${result.key}`;
                                    console.log('result↓');
                                    console.log(result);
                                    console.log('fileKey：' + fileKey);
                                    request({
                                        url: '/yoga_business/wechat/qiniu/generateSignedUrl',
                                        method: 'POST',
                                        data: {
                                            "fileKey": fileKey
                                        },
                                        success(res) {
                                            if (res.success) {
                                                if (typeof successCallback === 'function') {
                                                    successCallback(res.content);
                                                }
                                            } else {
                                                if (typeof failCallback === 'function') {
                                                    failCallback(res.message);
                                                }
                                            }
                                        },
                                        fail(msg) {
                                            if (typeof failCallback === 'function') {
                                                failCallback(msg);
                                            }
                                        }
                                    });
                                } else {
                                    wx.showToast({ title: '上传失败', icon: 'none' });
                                }
                            },
                            fail: (err) => {
                                console.error('上传失败:', err);
                                wx.showToast({ title: '上传请求失败', icon: 'none' });
                            }
                        });
                    } else {
                        if (typeof failCallback === 'function') {
                            failCallback(res.message);
                        }
                    }
                },
                fail(msg) {
                    console.log('POST请求失败', msg);
                    if (typeof failCallback === 'function') {
                        failCallback(msg);
                    }
                }
            });
        }
    });
}

function uploadQNImg(options) {
    //调用后端接口获取七牛云上次token
    uptoken = getQiuNiuUpToken();
    console.log("uptoken：");
    console.log(uptoken)
    if(!uptoken){
        showTip("获取上传凭证失败");
        return;
    }
    // 选择文件并上传
    wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (imageRes) => {
            const filePath = imageRes.tempFilePaths[0];
            const fileName = new Date().getTime() + '.jpg';
            // 3. 上传到七牛云
            wx.uploadFile({
                url: 'https://up.qiniup.com',
                filePath,
                name: 'file',
                formData: {
                    key: fileName,
                    token: uptoken
                },
                success: (uploadRes) => {
                    if (uploadRes.statusCode === 200) {
                        const result = JSON.parse(uploadRes.data);
                        const fileUrl = `${qiniuDomain}/${result.key}`;
                        console.log('result↓');
                        console.log(result);
                        console.log('fileUrl：'+fileUrl);
                        wx.showToast({ title: '上传成功', icon: 'none' });
                        this.setData({ uploadStatus: `已上传：${fileUrl}` });
                    } else {
                        wx.showToast({ title: '上传失败', icon: 'none' });
                    }
                },
                fail: (err) => {
                    console.error('上传失败:', err);
                    wx.showToast({ title: '上传请求失败', icon: 'none' });
                }
            });
        }
    });
}

/**
 * 获取七牛云上传token
 * @returns {*}
 */
function getQiuNiuUpToken(){
    //这里进行同步返回
    return requestPromise({
        url:'/yoga_business/wechat/qiniu/getUploadToken',
        method:'GET',
        data:{
        },
        success(res) {
            if(res.success){
                return res.content.content;
            }else{
                showTip(res.message);
            }
        },
        fail(msg) {
            console.log('POST请求失败', msg);
        }
    })
}

// 文件下载（直接使用七牛云文件链接）
const downloadUrl = 'your_qiniu_file_url';
wx.downloadFile({
    url: downloadUrl,
    success: function (res) {
        if (res.statusCode === 200) {
            const tempFilePath = res.tempFilePath;
            wx.saveImageToPhotosAlbum({
                filePath: tempFilePath,
                success: function () {
                    console.log('文件下载并保存成功');
                },
                fail: function (err) {
                    console.error('文件保存失败，错误信息：', err);
                }
            });
        } else {
            console.error('文件下载失败，状态码：', res.statusCode);
        }
    },
    fail: function (err) {
        console.error('文件下载失败，错误信息：', err);
    }
});

module.exports = {
    uploadQNImg,
    uploadImageToQiniu
};